#include "gcpch.h"
#include "gui_globals.h"
#include "gui_mainwnd.h"
#include "gui_listpane.h"
#include "gui_styleset.h"
#include "diritem_pool.h"

// test
#include "virtdir.h"
#include "virtdir_filesystem.h"
#include "virtdir_processor.h"
// end test

HINSTANCE geek_gui_app_hinstance = NULL;
HINSTANCE geek_gui_geekcmd_hinstance = NULL;
int geek_version_major = 0;
int geek_version_minor = 0;
int geek_version_patch = 0;

static geek_gui_mainwnd g_mainwnd;
static geek_gui_listpane g_listpanes[geek_gui_lpix_count];

static bool get_version_info()
{
    HRSRC version_resource = FindResource(geek_gui_app_hinstance,MAKEINTRESOURCE(VS_VERSION_INFO),RT_VERSION);
    if(version_resource == NULL)
    {
        return false;
    }

    HGLOBAL version_hglobal = LoadResource(geek_gui_app_hinstance,version_resource);
    if(version_hglobal == NULL)
    {
        return false;
    }

#pragma pack(push,1)
    struct version_info_struct
    {
        WORD ignored1[20];
        VS_FIXEDFILEINFO value;
    };
#pragma pack(pop)

    version_info_struct *version_info = (version_info_struct*)LockResource(version_hglobal);
    if(version_info == NULL)
    {
        return false;
    }

    geek_version_major = version_info->value.dwProductVersionMS >> 16;
    geek_version_minor = version_info->value.dwProductVersionMS & 0xffff;
    geek_version_patch = version_info->value.dwProductVersionLS >> 16;
    return true;
}

static bool init()
{
    return get_version_info() &&
        geek_diritem_pool_init() &&
        geek_gui_styleset_init() &&
        geek_gui_mainwnd_init() &&
        geek_gui_listpane_init() &&
        geek_gui_mainwnd_create(&g_mainwnd,g_listpanes);
}

static void deinit()
{
    geek_gui_mainwnd_destroy(&g_mainwnd);
    geek_gui_listpane_deinit();
    geek_gui_mainwnd_deinit();
    geek_gui_styleset_deinit();
    geek_diritem_pool_deinit();
}

static void run(int show)
{
    ShowWindow(g_mainwnd.hwnd,show);

    while(geek_gui_mainwnd_msgloop_cycle())
        ;
}

int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR /*cmdline*/, int show)
{
    geek_gui_app_hinstance = GetModuleHandle(NULL);
    geek_gui_geekcmd_hinstance = geek_gui_app_hinstance;

    if(!init())
    {
        MessageBox(NULL,L"Geek Commander failed to initialize",L"Geek Commander",MB_OK|MB_ICONERROR);
    }
    else
    {
        run(show);
    }

    deinit();

    CoUninitialize();
    return 0;
}
